<script>

import MapDialog from "./components/MapDialog.vue";
import SaveDialog from "./components/SaveDialog.vue";
import KtMap from "/src/components/common/KtMap.vue";
import SensorDialog from "./components/SensorDialog.vue";
import iot from "/src/js/iot/index.js";


export default {
  components: {KtMap, SaveDialog, MapDialog, SensorDialog},
  data() {
    return {
      iot,
      mapLoaded: true,
      bodyData: [

      ],
      requestParamBind: {
        name: "",
        projectId: ""
      },
      contentLoading: true,
      type: "card",
      mapBodyData: {
        center: {
          longitude: 103.8198,
          latitude: 1.3521
        },
        markers: [
          {
            latitude: 1.3521,
            longitude: 103.8198,
            title: "新加坡"
          }
        ]
      },
      projectList: [],
    }
  },
  async created() {
    await this.getProjectList();
    this.getAll();
  },
  mounted() {

  },
  methods: {
    getProjectList() {
      return new Promise((resolve, reject) => {
        this.$kt.request.send({
          uri: "/business-iot-web/admin/iotProject/getAll",
          data: {
          },
          stateSuccess: (res) => {
            this.projectList = res.data;
            // 默认选择第一个
            if (this.projectList.length > 0) {
              this.requestParamBind.projectId = this.projectList[0].id;
            }
            resolve();
          },
          stateFail: (err) => {
            this.$message.error(err.errMsg);
            reject();
          }
        });
      });
    },
    // 初始化mapBodyData
    initMapBodyData() {
      this.mapLoaded = false;
      this.mapBodyData = {
        center: {
          longitude: 103.8198,
          latitude: 1.3521
        },
        markers: []
      };
      // 将bodyData中的数据转换为mapBodyData的markers
      this.bodyData.forEach(item => {
        this.mapBodyData.markers.push({
          latitude: item.latitude,
          longitude: item.longitude,
          title: item.name
        });
      });
      setTimeout(() => {
        this.mapLoaded = true;
      }, 100);
    },
    toRemove(item) {
      // 是否确定删除,
      this.$confirm(this.$i18n.zhToGlobal('是否确定删除？'), this.$i18n.zhToGlobal('提示'), {
        confirmButtonText: this.$i18n.zhToGlobal('确定'),
        cancelButtonText: this.$i18n.zhToGlobal('取消'),
        type: 'warning',
      }).then(() => {
        this.contentLoading = true;
        this.$kt.request.send({
          uri: "/business-iot-web/admin/iotDevice/remove",
          data: {
            id: item.id
          },
          stateSuccess: (res) => {
            this.getAll();
            this.contentLoading = false;
          },
          stateFail: (err) => {
            this.$message.error(err.errMsg);
            this.contentLoading = false;
          }
        });
      }).catch(() => {
      });
    },
    toMap(item) {
      this.$refs.mapDialog.open(item.title, {
        center: {
          longitude: item.longitude,
          latitude: item.latitude
        },
        markers: [
          {
            latitude: item.latitude,
            longitude: item.longitude,
            title: ""
          }
        ]
      });
    },
    getAll() {
      this.contentLoading = true;
      this.$kt.request.send({
        uri: "/business-iot-web/admin/iotDevice/getAll",
        data: {
          and: [{
            field: "name",
            value: this.requestParamBind.name,
            operatorCode: "vague"
          },{
            field: "projectId",
            value: this.requestParamBind.projectId,
            operatorCode: "eq"
          }]
        },
        stateSuccess: (res) => {
          this.contentLoading = false;
          this.bodyData = res.data;
          // 按照优先级排序
          this.bodyData.sort((a, b) => {
            return b.priority - a.priority;
          });
          this.initMapBodyData();
        },
        stateFail: (err) => {
          this.$message.error(err.errMsg);
          this.contentLoading = false;
        }
      });
    },
    selectProject(item) {
      this.requestParamBind.projectId = item.id;
      this.getAll();
    },
    /**
     * 判断是否在线
     */
    isOnline(item) {
      // 判断最后一次心跳时间是否超过设置的间隔
      if (item.online?.gmtLastHeartbeat) {
        const gmtLastHeartbeat = new Date(item.online?.gmtLastHeartbeat).getTime();
        const now = new Date().getTime();
        const interval = item.interval * 1000 + 1000;
        if (now - gmtLastHeartbeat < interval) {
          return true;
        }
      }
      return false;
    }
  }
}
</script>

<template>
  <div>
    <map-dialog
        ref="mapDialog"
    ></map-dialog>

    <save-dialog
        @save="getAll"
        ref="saveDialog"></save-dialog>
    <div style="display: inline-block;width: 180px;height: 100vh">
      <div style="font-weight: bold;font-size: 16px;text-align: center">{{$i18n.zhToGlobal("项目列表")}}</div>
      <div style="height: 10px"></div>
      <el-scrollbar style="height: calc(100vh - 60px)">
        <div
            style="padding: 10px;box-sizing: border-box"
            v-for="item in projectList">
          <div class="card-project"
          :class="{
            'card-project-selected': requestParamBind.projectId === item.id
          }"
               @click="selectProject(item)"
          >
            {{ item.title }}
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div style="position: relative;display: inline-block;width: calc(100vw - 200px);margin-left: 10px;height: 100vh;vertical-align: top;">

      <div
          style="position: relative">

        <el-form
            @submit.native.prevent
        >
          <el-form-item :label="$i18n.zhToGlobal('设备名称')">
            <el-input
                style="width: 200px"
                :placeholder="$i18n.zhToGlobal('设备名称')"
                v-model="requestParamBind.name"
                @keyup.enter.native="getAll"
            ></el-input>
          </el-form-item>
        </el-form>

        <div style="position: absolute;right: 0;top: 0">
          <!-- 刷新 -->
          <el-button
              type="primary"
              @click="getAll">
            <kt-icon
                class="el-icon-refresh"
                color="#fff"
                @click="getAll"
                icon="el-icon-refresh">
            </kt-icon>
          </el-button>

          <el-button
              type="primary"
              @click="$refs.saveDialog.openNew(requestParamBind.projectId)">
            <kt-icon
                class="icon-add"
                color="#fff"
                icon="el-icon-plus">
            </kt-icon>
          </el-button>
        </div>
      </div>


    <el-scrollbar
          v-if="type === 'card'"
          v-loading="contentLoading"
          class="scrollbar-box">

        <!-- 更改头部颜色 -->
        <el-table
            :data="bodyData"
            style="width: 100%"
            border
            height="calc(100vh - 120px)">

          <el-table-column
              prop="id"
              :label="$i18n.zhToGlobal('网关ID')"
              width="200">
          </el-table-column>

          <!-- 是否在线 -->
          <el-table-column
              prop="online"
              :label="$i18n.zhToGlobal('状态')"
              width="100">
            <template #default="scope">
              <el-tag v-if="isOnline(scope.row)"
                type="success">
                {{$i18n.zhToGlobal('在线')}}
              </el-tag>
              <el-tag v-else
                type="danger">
                {{$i18n.zhToGlobal('离线')}}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
              prop="sn"
              :label="$i18n.zhToGlobal('设备的SN')"
              width="200">
          </el-table-column>

          <el-table-column
              prop="name"
              :label="$i18n.zhToGlobal('设备名称')"
              width="180">
          </el-table-column>


          <el-table-column
              width="200"
              :label="$i18n.zhToGlobal('经纬度')">
            <template #default="scope">
              <div
                  class="card-lon-lat"
                  @click="toMap(scope.row)"
              >
                <kt-icon icon="ant-icon-compass-outlined"
                         color="#000"
                ></kt-icon>
                <span style="margin-left:10px;vertical-align: top;display: inline-block">{{
                    scope.row.longitude
                  }} , {{ scope.row.latitude }}</span>
              </div>
            </template>
          </el-table-column>

          <!-- 设备协议 -->
          <el-table-column
              width="200"
              prop="protocolCode"
              :label="$i18n.zhToGlobal('设备协议')">
            <template #default="scope">
            <el-tag>
              {{ iot.getProtocolLabel(scope.row.protocolCode) }}
            </el-tag>
            </template>
          </el-table-column>



          <!-- 上传周期 -->
          <el-table-column
              prop="interval"
              width="180"
              :label="`${$i18n.zhToGlobal('间隔')}[${$i18n.zhToGlobal('秒')}]`">
          </el-table-column>

          <!-- 优先级 -->
          <el-table-column
              prop="priority"
              :label="$i18n.zhToGlobal('优先级')">
          </el-table-column>
          <el-table-column
              fixed="right"
              :label="$i18n.zhToGlobal('操作')"
              width="180">
            <template #header>
              <div style="text-align: center">
                {{$i18n.zhToGlobal('操作')}}
              </div>
            </template>
            <template #default="scope">
              <div style="text-align: center">
                <div>
                  <kt-icon
                      @click="$refs.saveDialog.open(scope.row)"
                      icon="ant-icon-edit-outlined"
                      color="#000"
                      class="icon-edit icon-btn"
                  ></kt-icon>
                  <kt-icon
                      @click="toRemove(scope.row)"
                      icon="el-icon-delete"
                      color="#ff0000"
                      style="margin-left: 20px"
                      class="icon-delete icon-btn"
                  ></kt-icon>
                </div>
                <div>
                  <el-button
                  @click="()=>this.$refs.sensorDialog.open(scope.row)"
                  >{{$i18n.zhToGlobal('传感器列表')}}</el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>


        <div
            v-if="false"
            class="card" v-for="item in bodyData">
          <div class="card-header">
            <div class="card-title">
              {{ item.title }}
              <span
                  class="card-sn"
              >#{{ item.sn }}</span>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text">
              <el-scrollbar class="scrollbar">
                <div>{{ item.description }}</div>
              </el-scrollbar>
            </div>
            <div
                class="card-lon-lat"
                @click="toMap(item)"
            >
              <kt-icon icon="ant-icon-compass-outlined"
                       color="#000"
                       style="vertical-align: bottom"
              ></kt-icon>
              {{ item.longitude }} , {{ item.latitude }}
            </div>
            <div
                style="position: absolute;bottom: 15px;right: 10px"
            >
              <kt-icon
                  @click="()=>this.$refs.saveDialog.open(item)"
                  icon="ant-icon-edit-outlined"
                  color="#000"
                  class="icon-edit icon-btn"
              ></kt-icon>
              <kt-icon
                  style="margin-left: 10px"
                  color="#ff0000"
                  icon="el-icon-delete"
                  class="icon-delete icon-btn"
                  @click="toRemove(item)"
              ></kt-icon>
            </div>
          </div>
        </div>

      </el-scrollbar>


      <div class="map-box"
           v-if="type === 'map'"
      >
        <kt-map
            v-if="mapLoaded"
            :data="mapBodyData"></kt-map>
      </div>

      <div class="bottom">
        <el-button
            :type="type === 'card'?'primary':''"
            @click="()=>type = 'card'"
        >{{ $i18n.zhToGlobal('列表模式') }}
        </el-button>
        <el-button
            :type="type === 'map'?'primary':''"
            @click="()=>type = 'map'"
        >{{ $i18n.zhToGlobal('地图模式') }}
        </el-button>
      </div>

      <el-button
          style="position: absolute;bottom:10px;right:10px"
      >{{ $i18n.zhToGlobal('打开仪表盘') }}
      </el-button>

    </div>


    <sensor-dialog
        ref="sensorDialog"></sensor-dialog>

  </div>
</template>

<style scoped lang="scss">

.card {
  position: relative;
  margin: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 5px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
  width: 300px;
  display: inline-block;

  .card-header {
    padding: 10px;
    border-bottom: 1px solid #e8e8e8;

    .card-title {
      font-size: 16px;
      font-weight: bold;

      .card-sn {
        font-size: 12px;
        font-weight: lighter;
        margin-left: 10px;
        float: right;
      }
    }

  }

  .card-body {
    padding: 10px;

    .card-text {
      font-size: 14px;
    }
  }
}

.scrollbar {
  height: 100px;
  overflow: auto;
  padding: 10px;

  .el-scrollbar__wrap {
    padding: 0;
  }

  .el-scrollbar__view {
    padding: 0;
  }

  .el-scrollbar__bar {
    background-color: #e8e8e8;
  }

  .el-scrollbar__thumb {
    background-color: #999;
  }
}

.card-lon-lat {
  font-size: 12px;
  font-weight: lighter;
  padding: 10px;
  cursor: pointer;
}

.card-lon-lat:hover {
  opacity: .6;
}

.card-lon-lat:active {
  opacity: 1;
}

.icon-edit {
  cursor: pointer;
}

.icon-delete {
  cursor: pointer;
}

.icon-btn:hover {
  transform: scale(1.1);
}

.icon-btn:active {
  transform: scale(1);
}

.scrollbar-box {
  height: calc(100vh - 120px);
  padding: 10px;
  text-align: center;
}

.bottom {
  position: absolute;
  bottom: 10px;
}

.map-box {
  width: 100%;
  height: calc(100vh - 120px);
  border-radius: 5px;
  overflow: hidden;
}

.card-project {
  padding: 10px;
  cursor: pointer;
  background-color: #f8f8f8;
  border-radius: 20px;
  text-align: center;
}

.card-project-selected {
  background-color: #333;
  color: #fff;
}
</style>